<?php
/**
 * 最终验证脚本 - 验证所有优化是否正常工作
 */

echo "==========================================\n";
echo "  客户管理模块优化 - 最终验证\n";
echo "  " . date('Y-m-d H:i:s') . "\n";
echo "==========================================\n\n";

$allPassed = true;

// 引入自动加载
require dirname(__DIR__, 2) . '/vendor/autoload.php';

// 初始化ThinkPHP应用
$app = new \think\App();
$app->initialize();

// 1. 验证Customer模型加载
echo "1. 验证Customer模型加载...\n";
try {
    $customerModel = new \app\model\customer\Customer();
    echo "   ✓ Customer模型加载成功\n\n";
} catch (Exception $e) {
    echo "   ✗ Customer模型加载失败: " . $e->getMessage() . "\n\n";
    $allPassed = false;
}

// 2. 验证数据刷新功能
echo "2. 验证数据刷新功能...\n";
try {
    $startTime = microtime(true);
    $result = $customerModel->refreshAllBusinessData();
    $duration = microtime(true) - $startTime;
    if ($result) {
        echo "   ✓ 数据刷新成功，耗时: " . number_format($duration, 2) . " 秒\n\n";
    } else {
        echo "   ✗ 数据刷新失败\n\n";
        $allPassed = false;
    }
} catch (Exception $e) {
    echo "   ✗ 数据刷新异常: " . $e->getMessage() . "\n\n";
    $allPassed = false;
}

// 3. 验证数据字段存在
echo "3. 验证新增业务字段...\n";
try {
    $pdo = new PDO('mysql:host=localhost;dbname=oa5;charset=utf8mb4', 'root', '123456');

    // 检查字段是否存在
    $stmt = $pdo->query("SHOW COLUMNS FROM oa_customer LIKE 'is_member'");
    if ($stmt->rowCount() > 0) {
        echo "   ✓ 字段 is_member 存在\n";
    }

    $stmt = $pdo->query("SHOW COLUMNS FROM oa_customer LIKE 'contract_num'");
    if ($stmt->rowCount() > 0) {
        echo "   ✓ 字段 contract_num 存在\n";
    }

    $stmt = $pdo->query("SHOW COLUMNS FROM oa_customer LIKE 'case_num'");
    if ($stmt->rowCount() > 0) {
        echo "   ✓ 字段 case_num 存在\n";
    }

    echo "   ✓ 所有新增字段存在\n\n";
} catch (Exception $e) {
    echo "   ✗ 字段验证失败: " . $e->getMessage() . "\n\n";
    $allPassed = false;
}

// 4. 验证数据完整性
echo "4. 验证数据完整性...\n";
try {
    $stmt = $pdo->query("
        SELECT
            COUNT(*) AS total,
            SUM(is_member = 1) AS members,
            SUM(contract_num > 0) AS has_contracts,
            SUM(case_num > 0) AS has_cases
        FROM oa_customer
        WHERE delete_time = 0 AND discard_time = 0
    ");
    $stats = $stmt->fetch();

    echo "   总客户: {$stats['total']}\n";
    echo "   会员客户: {$stats['members']}\n";
    echo "   有合同客户: {$stats['has_contracts']}\n";
    echo "   有案件客户: {$stats['has_cases']}\n\n";

    if ($stats['total'] > 0) {
        echo "   ✓ 数据完整性验证通过\n\n";
    } else {
        echo "   ✗ 未找到有效客户数据\n\n";
        $allPassed = false;
    }
} catch (Exception $e) {
    echo "   ✗ 数据完整性验证失败: " . $e->getMessage() . "\n\n";
    $allPassed = false;
}

// 5. 验证性能提升
echo "5. 验证性能提升...\n";
try {
    // 测试新方式查询
    $start = microtime(true);
    $stmt = $pdo->query("
        SELECT id, name, is_member, contract_num, contract_amount, case_num
        FROM oa_customer
        WHERE delete_time = 0 AND discard_time = 0
        ORDER BY id DESC
        LIMIT 10
    ");
    $durationNew = (microtime(true) - $start) * 1000;
    $rows = $stmt->fetchAll();

    echo "   新方式查询时间: " . number_format($durationNew, 2) . " ms\n";
    echo "   返回记录数: " . count($rows) . "\n";

    if ($durationNew < 10) {
        echo "   ✓ 查询性能优秀 (<10ms)\n\n";
    } else {
        echo "   ⚠ 查询性能一般 (>=10ms)\n\n";
    }
} catch (Exception $e) {
    echo "   ✗ 性能测试失败: " . $e->getMessage() . "\n\n";
    $allPassed = false;
}

// 6. 验证定时任务脚本
echo "6. 验证定时任务脚本...\n";
$scriptPath = __DIR__ . '/refresh_business_data.php';
if (file_exists($scriptPath)) {
    echo "   ✓ 脚本文件存在: refresh_business_data.php\n";

    // 检查脚本权限
    if (is_readable($scriptPath)) {
        echo "   ✓ 脚本可读\n";
    }

    echo "   ✓ 定时任务脚本验证通过\n\n";
} else {
    echo "   ✗ 脚本文件不存在: refresh_business_data.php\n\n";
    $allPassed = false;
}

// 7. 验证配置文档
echo "7. 验证配置文档...\n";
$docPath = __DIR__ . '/CRON_SETUP.md';
if (file_exists($docPath)) {
    echo "   ✓ 配置文档存在: CRON_SETUP.md\n";
    echo "   ✓ 定时任务配置文档验证通过\n\n";
} else {
    echo "   ✗ 配置文档不存在: CRON_SETUP.md\n\n";
    $allPassed = false;
}

// 8. 检查模型备份
echo "8. 检查模型备份...\n";
$backupPath = dirname(__DIR__, 2) . '/app/model/customer/Customer_old.php';
if (file_exists($backupPath)) {
    echo "   ✓ 原始模型备份存在\n\n";
} else {
    echo "   ⚠ 原始模型备份不存在\n\n";
}

// 9. 验证日志文件
echo "9. 验证日志文件...\n";
$logPath = __DIR__ . '/refresh_log.txt';
if (file_exists($logPath)) {
    echo "   ✓ 执行日志存在\n";
} else {
    echo "   ℹ 执行日志尚未生成（首次运行后会创建）\n";
}

$errorLogPath = __DIR__ . '/refresh_error_log.txt';
if (file_exists($errorLogPath)) {
    echo "   ✓ 错误日志存在\n\n";
} else {
    echo "   ℹ 错误日志尚未生成\n\n";
}

// 最终结果
echo "==========================================\n";
echo "  验证结果\n";
echo "==========================================\n\n";

if ($allPassed) {
    echo "✅ 所有验证通过！\n";
    echo "\n优化状态: 全部完成，可投入使用\n";
    echo "\n下一步行动:\n";
    echo "1. 配置crontab定时任务\n";
    echo "2. 测试前端页面展示\n";
    echo "3. 监控查询性能\n\n";
} else {
    echo "⚠ 部分验证未通过，请检查上述错误\n\n";
}

echo "==========================================\n";
echo "  验证完成\n";
echo "==========================================\n";
